﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using NigiriClub.WebUI.Models;
using NigiriClub.WebUI.Models.PagedCollections;

namespace NigiriClub.WebUI.Controllers
{

    public class HomeController : Controller
    {
        //
        // GET: /Home/
        [ValidateInput(false)]
        public ActionResult Index(int page = 1, string tag = "", string category = "")
        {
            ViewBag.Tag = tag;
            ViewBag.Category = category;
            return View(new NewswireViewModel(page, tag, category));
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddNews(News news)
        {
            news.AddToDb(User.Identity.Name);
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult EditNews(int id)
        {
            News edited;
            using (Entities db = new Entities())
            {
                edited = db.News.FirstOrDefault(n => n.Id == id);
                if (edited == null)
                {
                    //todo error message
                    return RedirectToAction("Index", "Home");
                }
            }
            return View(edited);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult _EditNews(News news)
        {
            news.Edit();
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult DeleteNews(int id)
        {
            using (Entities db = new Entities())
            {
                News news = db.News.FirstOrDefault(n => n.Id == id);
                news.Tag.Clear();
                db.News.Remove(news);
                db.SaveChanges();
            }

            return RedirectToAction("Index", "Home");
        }
    }
}
